requireJS(['constant' , 'site', 'handlebars' ,'uploadimage'] , function ( Constant , site ,Handlebars ,uploadimage ) {

    //注册handlebars
    Constant.initHandlebars(Handlebars);
    //表单验证同时阻止程序继续运行

    var oss = {
        url:'',
        accessId:'',
        host :'',
        policyBase64 :'',
        signature :'',
        callback :'',
        filename :'',
        key : '',
        expire : 0,
        g_object_name : '',
        g_object_name_type : '',
        now : timestamp = Date.parse(new Date()) / 1000
    }

    var url = {
        getSignature:"manager/getSignature.do"
    }


    function getSignature(){
        site.send({

            url:url.getSignature,
            //async:false,
            callback:function(data){
                data = JSON.parse(data)
                if(data.type == 1){
                    var content = data.content;
                    oss.host = content.host;
                    oss.policyBase64 = content.policy;
                    oss.accessId = content.accessId;
                    oss.signature = content.signature;
                    oss.expire = content.expire;
                    oss.callback = content.callback;
                    oss.key = content.dir;
                }
            }
        })
    }

    function check_object_radio() {
        var tt = document.getElementsByName('myradio');
        for (var i = 0; i < tt.length ; i++ )
        {
            if(tt[i].checked)
            {
                g_object_name_type = tt[i].value;
                break;
            }
        }
    }

    function get_signature()
    {
        //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
        now = timestamp = Date.parse(new Date()) / 1000;
        if (oss.expire < now + 3)
        {
            getSignature();
            return true;
        }
        return false;
    };

    function random_string(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    function calculate_object_name(filename)
    {
        if (g_object_name_type == 'local_name')
        {
            g_object_name += "${filename}"
        }
        else if (g_object_name_type == 'random_name')
        {
            suffix = get_suffix(filename)
            g_object_name = key + random_string(10) + suffix
        }
        return ''
    }

    function get_uploaded_object_name(filename)
    {
        if (g_object_name_type == 'local_name')
        {
            tmp_name = g_object_name
            tmp_name = tmp_name.replace("${filename}", filename);
            return tmp_name
        }
        else if(g_object_name_type == 'random_name')
        {
            return g_object_name
        }
    }

    function set_upload_param(up, filename, ret)
    {
        if (ret == false)
        {
            ret = get_signature()
        }
        g_object_name = oss.key;
        if (filename != '') { suffix = get_suffix(filename)
            calculate_object_name(filename)
        }
        new_multipart_params = {
            'key' : g_object_name,
            'policy': oss.policyBase64,
            'OSSAccessKeyId': oss.accessId,
            'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
            'callback' : oss.callback,
            'signature': oss.signature,
        };

        up.setOption({
            'url': oss.host,
            'multipart_params': new_multipart_params
        });

        up.start();
    }

    function getOssParam ( ) {
        get_signature();
        var g_object_name = oss.key;
        var new_multipart_params = {
            'key': g_object_name ,
            'policy': oss.policyBase64,
            'OSSAccessKeyId': oss.accessId,
            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
            'callback': oss.callback,
            'signature': oss.signature
        }
        return new_multipart_params;
    }

    $('#add-pic-box').uploadImage({isNeedDesc: false});
    $('#image_upload_pop').toggle();

    $('#submit').on('click' , function (){

        var imageFiles = $('#add-pic-box').data('uploadImageBox').getUploadFiles();
        var $error =  $('#add-pic-box').find('.modal-error');
        if(imageFiles.length < 1) {
            $error.html('上传图片不能为空');
        }else {
            $error.html('');

            $.each(imageFiles, function (name, value) {
                var param = getOssParam();
                param['file'] = value;
                param['key'] = param['key'] + '/' + name ;
                // param['pictures['+name+'].desc'] = value.desc;

                site.filesUpload({
                    url: oss.host,
                    isAbsoluteUrl:false,
                    data: param,
                    callSuccess: function ( data ) {
                        console.log( data );
                    },
                    callErrorWithCode: function (error) {
                        $error.html(error.message);
                    }
                });
            });
        }
    });
})







